{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "# Install openai-agents SDK"
      ],
      "metadata": {
        "id": "PdKwzEluDBN7"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install -Uq openai-agents"
      ],
      "metadata": {
        "id": "3QdkOviEB2ay",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "0db8d0c0-9881-4c23-e1c8-65036692a35a"
      },
      "execution_count": 1,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\u001b[?25l   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/76.1 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m76.1/76.1 kB\u001b[0m \u001b[31m2.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h\u001b[?25l   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/128.6 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m128.6/128.6 kB\u001b[0m \u001b[31m6.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h\u001b[?25l   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/567.4 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m567.4/567.4 kB\u001b[0m \u001b[31m15.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Make your Jupyter Notebook capable of running asynchronous functions."
      ],
      "metadata": {
        "id": "7yD91lz4DIAx"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import nest_asyncio\n",
        "nest_asyncio.apply()"
      ],
      "metadata": {
        "id": "7A5YLi3HCfBV"
      },
      "execution_count": 2,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Run Google Gemini with OPENAI-Agent SDK"
      ],
      "metadata": {
        "id": "K3VTUWDaGFcV"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import os\n",
        "from agents import Agent, Runner, AsyncOpenAI, OpenAIChatCompletionsModel\n",
        "from agents.run import RunConfig\n",
        "from google.colab import userdata\n",
        "\n",
        "from agents import (\n",
        "    Agent,\n",
        "    Runner,\n",
        "    set_default_openai_api,\n",
        "    set_default_openai_client,\n",
        "    set_tracing_disabled,\n",
        ")\n",
        "\n",
        "gemini_api_key = userdata.get(\"GEMINI_API_KEY\")\n",
        "\n",
        "\n",
        "# Check if the API key is present; if not, raise an error\n",
        "if not gemini_api_key:\n",
        "    raise ValueError(\"GEMINI_API_KEY is not set. Please ensure it is defined in your .env file.\")\n",
        "\n",
        "#Reference: https://ai.google.dev/gemini-api/docs/openai\n",
        "external_client = AsyncOpenAI(\n",
        "    api_key=gemini_api_key,\n",
        "    base_url=\"https://generativelanguage.googleapis.com/v1beta/openai/\",\n",
        ")\n",
        "\n",
        "model = OpenAIChatCompletionsModel(\n",
        "    model=\"gemini-2.0-flash\",\n",
        "    openai_client=external_client\n",
        ")\n",
        "\n",
        "set_default_openai_client(client=external_client, use_for_tracing=False)\n",
        "set_default_openai_api(\"chat_completions\")\n",
        "set_tracing_disabled(disabled=True)"
      ],
      "metadata": {
        "id": "QSIWS6RvC-a4"
      },
      "execution_count": 3,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Streaming Text code"
      ],
      "metadata": {
        "id": "FXBrF52IPBM9"
      }
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "IrgKhgyTYvEn"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "Tg583lQEBRWo",
        "outputId": "4acd1a69-86dd-4103-e4de-7bb54fcff67b"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Okay, here are 5 jokes for you:\n",
            "\n",
            "1.  Why don't scientists trust atoms?\n",
            "    Because they make up everything!\n",
            "\n",
            "2.  Why did the scarecrow win an award?\n",
            "    Because he was outstanding in his field!\n",
            "\n",
            "3.  What do you call a lazy kangaroo?\n",
            "    Pouch potato!\n",
            "\n",
            "4.  Why did the bicycle fall over?\n",
            "    Because it was two tired!\n",
            "\n",
            "5.  What musical instrument is found in the bathroom?\n",
            "    A tuba toothpaste!\n",
            "\n",
            "Hope you enjoyed those!\n"
          ]
        }
      ],
      "source": [
        "import asyncio\n",
        "\n",
        "from openai.types.responses import ResponseTextDeltaEvent\n",
        "\n",
        "from agents import Agent, Runner\n",
        "\n",
        "\n",
        "async def main():\n",
        "    agent = Agent(\n",
        "        name=\"Joker\",\n",
        "        instructions=\"You are a helpful assistant.\",\n",
        "        model=model\n",
        "    )\n",
        "\n",
        "    result = Runner.run_streamed(agent, input=\"Please tell me 5 jokes.\")\n",
        "    async for event in result.stream_events():\n",
        "        if event.type == \"raw_response_event\" and isinstance(event.data, ResponseTextDeltaEvent):\n",
        "            print(event.data.delta, end=\"\", flush=True)\n",
        "\n",
        "\n",
        "\n",
        "asyncio.run(main())"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Stream item code"
      ],
      "metadata": {
        "id": "pikemA8-SV0u"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import asyncio\n",
        "import random\n",
        "\n",
        "from agents import Agent, ItemHelpers, Runner, function_tool\n",
        "\n",
        "\n",
        "@function_tool\n",
        "def how_many_jokes() -> int:\n",
        "    return random.randint(1, 10)\n",
        "\n",
        "\n",
        "async def main():\n",
        "    agent = Agent(\n",
        "        name=\"Joker\",\n",
        "        instructions=\"First call the `how_many_jokes` tool, then tell that many jokes.\",\n",
        "        tools=[how_many_jokes],\n",
        "        model=model\n",
        "    )\n",
        "\n",
        "    result = Runner.run_streamed(\n",
        "        agent,\n",
        "        input=\"Hello\",\n",
        "\n",
        "    )\n",
        "    print(\"=== Run starting ===\")\n",
        "    async for event in result.stream_events():\n",
        "        # We'll ignore the raw responses event deltas\n",
        "        if event.type == \"raw_response_event\":\n",
        "            continue\n",
        "        elif event.type == \"agent_updated_stream_event\":\n",
        "            print(f\"Agent updated: {event.new_agent.name}\")\n",
        "            continue\n",
        "        elif event.type == \"run_item_stream_event\":\n",
        "            if event.item.type == \"tool_call_item\":\n",
        "                print(\"-- Tool was called\")\n",
        "            elif event.item.type == \"tool_call_output_item\":\n",
        "                print(f\"-- Tool output: {event.item.output}\")\n",
        "            elif event.item.type == \"message_output_item\":\n",
        "                print(f\"-- Message output:\\n {ItemHelpers.text_message_output(event.item)}\")\n",
        "            else:\n",
        "                pass  # Ignore other event types\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "\n",
        "asyncio.run(main())\n",
        "\n",
        "print(\"=== Run complete ===\")"
      ],
      "metadata": {
        "id": "pTNf1noxCRi-",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "7b836eb3-0c84-47b0-ea6d-a3cf71dcb38e"
      },
      "execution_count": 5,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "=== Run starting ===\n",
            "Agent updated: Joker\n",
            "-- Tool was called\n",
            "-- Tool output: 8\n",
            "-- Message output:\n",
            " Ok, I will tell you 8 jokes.\n",
            "\n",
            "Why don't scientists trust atoms?\n",
            "Because they make up everything!\n",
            "\n",
            " параллелепипед\n",
            "\n",
            "Why did the scarecrow win an award?\n",
            "Because he was outstanding in his field!\n",
            "\n",
            "What do you call a fish with no eyes?\n",
            "Fsh!\n",
            "\n",
            "Why did the bicycle fall over?\n",
            "Because it was two tired!\n",
            "\n",
            "What do you call a bear with no teeth?\n",
            "A gummy bear!\n",
            "\n",
            "Why did the teddy bear say no to dessert?\n",
            "Because she was stuffed.\n",
            "\n",
            "What musical instrument is found in the bathroom?\n",
            "A tuba toothpaste.\n",
            "\n",
            "=== Run complete ===\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "741wmWdpS22Z"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}